var
    gulp = require('gulp'),                             //本地安装gulp所用到的地方
    less = require('gulp-less'),                        //less编译
    autoprefixer = require('gulp-autoprefixer'),        //自动前缀
    minify = require('gulp-clean-css'),                //css压缩
    uglify = require('gulp-uglify'),                    //js压缩
    concat = require('gulp-concat'),                    //js合并
    notify = require('gulp-notify'),                    //编译提示
    watch = require('gulp-watch'),                      //变动监听
    rename = require('gulp-rename'),                    //更改名称
    rev = require('gulp-rev'),                          //生成MD5 版本manifest
    revReplace = require('gulp-rev-replace');           //替换引用路径
    //++++++++
    sourcemaps = require('gulp-sourcemaps');            //
    plumber = require('gulp-plumber');                  //避免因错误而中断 gulp
    revReplace = require('gulp-rev-replace');           //替换引用路径
    runSequence  = require('run-sequence');             //独立任务
    //del = require('del');                             //删除文件
    useref = require('gulp-useref');                    //html引用文件合并
    cheerio = require('gulp-cheerio');

//路径
var path = {
    less:'views/',
    com:'src/',
    replaceInfo:{},

    concatCss:[
        './src/less/common/common.css',
        './src/less/common/grid.css',
        './src/less/common/icon.css',
        './src/less/index.css',
        './src/component/com-component-20190601.min.css',
        './src/component/quill/quill.snow.css'
    ],
    concatJs:[
        './src/lib/jquery-latest.js',
        './src/js/ajax.js',
        './src/js/common.js',
        './src/lib/director.js',
        './src/lib/template-web.js',
        './src/component/com-component-20190601.min.js',
    ],
    out:'dist/',
    html:'views/'
};

//data******************************************
//监听模块样式变动
gulp.task('data-watch', function() {
    gulp.watch(path.less + '**/*.less',function(event){
        var str = event.path;
            //str = str.match(/less\\(.+)\.less$/)[1];
            str = str.match(/\\([a-zA-Z-_0-9]+)\.less$/)[1];
        var watchName = str.replace(/\\/,'/');
        return  gulp.src(path.less + '**/' + watchName +'.less')
            .pipe(less())
            .pipe(autoprefixer())
            //.pipe(cssmin())
            .pipe(gulp.dest(path.less))
            //.pipe(notify({ message: 'Css编译完成' }));
            //gulp.start('data-style');
    });
});
//监听组件样式变动
gulp.task('com-watch', function() {
    gulp.watch(path.com + '**/*.less',function(event){
        var str = event.path;
        //str = str.match(/less\\(.+)\.less$/)[1];
        str = str.match(/\\([a-zA-Z-_0-9]+)\.less$/)[1];
        var watchName = str.replace(/\\/,'/');
        return  gulp.src(path.com + '**/' + watchName +'.less')
            .pipe(less())
            .pipe(autoprefixer())
            //.pipe(cssmin())
            .pipe(gulp.dest(path.com))
            .pipe(notify({ message: 'Css编译完成' }));
        //gulp.start('data-style');
    });
});

gulp.task('less-all', function () {
    return  gulp.src(path.less + "**/*.less")
        .pipe(less())
        .pipe(autoprefixer())
        .pipe(minify({}))
        .pipe(gulp.dest(path.less))
        .pipe(notify({ message: 'Css编译完成' }));
});

//公共所有样式
gulp.task('com-all', function () {
    return  gulp.src(path.com + "**/*.less")
        .pipe(less())
        .pipe(autoprefixer())
        .pipe(minify({}))
        .pipe(gulp.dest(path.com))
        .pipe(notify({ message: 'Css编译完成' }));
});




/**
 ** @线上打包相关
 ** @发布dist包：
 ** @执行 gulp build-html
 **/

gulp.task('getCss', function() {
    return gulp.src([path.less + "/**/*.css",path.com + 'component/**/*.css']).on('data', function(file) {
        var name = file.path.replace(/\\/g,'/');//replace(/css$/,'html')
            name = name.match(/email-admin(.+)/)[1];
        var val = file.contents;
        path.replaceInfo[name] = val;
    });
});

gulp.task('setCss', function() {
    return gulp.src(path.less + "**/*.html",{ base:'.'})
        .pipe(cheerio(function ($,file) {
            //var name = file.path.replace(/\\/g,'/');
            //var cssStr = "<style>" + path.replaceInfo[name].toString() + "</style>";
            var str = "";
            $('link').each(function(index,item){ //"E:/xampp/htdocs/www/email-admin"
                var href = $(item).prop('href');
                if(path.replaceInfo[href]){
                    str += path.replaceInfo[href].toString();
                    $(this).remove();
                }
            });
            $('section').eq(0).prepend("<style>" + str + "</style>");
        }))
    .pipe(gulp.dest(path.out));
});

gulp.task('move',function(){
    return gulp.src('./src/**/*',{base:'.'})
        .pipe(gulp.dest(path.out));
});

//合并css文件并移动至目标文件夹
gulp.task('concatCss',function(){
    return gulp.src(path.concatCss)
        .pipe(concat('index.min.css'))
        .pipe(minify())
        .pipe(gulp.dest(path.out + 'src/less'));
});
//合并js文件移动至目标文件夹
gulp.task('concatJs',function(){
    return gulp.src(path.concatJs)
        .pipe(concat('index.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest(path.out + 'src/js'));
});

gulp.task('indexConcat',function(){
    return gulp.src('./index.html', {base: '.'})
        .pipe(useref({noAssets: true})) // 资源替换
        .pipe(gulp.dest(path.out));
});



//生成版本文件
gulp.task('rev', function () {
    return gulp.src([path.out+'src/**/*.css',path.out + 'src/js/**/*.js'])
        .pipe(rev())
        .pipe( rev.manifest() )
        .pipe(rename('rev.json'))
        .pipe( gulp.dest( path.out ) );
});

//添加版本号
gulp.task('rev-add', function() {
    var manifest = gulp.src(path.out + 'rev.json');
    var out = path.out;
    function modifyUnreved(filename) {
        return filename;
    }
    function modifyReved(filename) {
        var res = '';
        const version = filename.match(/-([a-z\d]+)\./)[1];
        const file = filename.replace(/-[a-z\d]+\./,'.');
        res = file + "?v=" + version;
        return res;
    }
    gulp.src([out + '*.html'])
        .pipe(revReplace({
            manifest: manifest,
            modifyUnreved: modifyUnreved,
            modifyReved: modifyReved
        }))
        .pipe(gulp.dest(out));
});

gulp.task('build-html',function(callback){
    runSequence('getCss','setCss',['move','indexConcat'],['concatCss','concatJs'],['rev'],['rev-add'],callback);
});